import { useEffect, useState } from "react";
import { Text, View, Image, WebView, Canvas, Snapshot } from "@tarojs/components";
import { Button, DatePicker, Picker } from "@nutui/nutui-react-taro";
import InfiniteLoading from "../../components/InfiniteLoading";
import InfiniteLoadingFoot from "../../components/InfiniteLoadingFoot";
import usePage from "../../hooks/usePage";
import { iconClear, iconClockBlack, iconCompany, iconDownGray, iconXiaqu, logo } from "../../assets/files";
import dayjs from "dayjs";
import Taro, { useDidShow, useLoad, useShareAppMessage } from "@tarojs/taro";
import { pageHidden, pageTrainingInfo } from "../../api/apply";
import { navigateTo } from "../../common/_";
import useNavInfo from "../../hooks/useNavInfo";
import { baseUrl } from "../../utils/request";
import ShareModal from "./components/share-modal";
import { shareWord } from "../../api/yinhuan";
import NavTab from "../../components/navTab";
import "./index.scss";


definePageConfig({
  navigationBarTitleText: "测试记录",
  disableScroll: true,
});

export default function DangerList(props) {
  const [timeStartVisible, setTimeStartVisible] = useState(false);
  const [shareVisible, setShareVisible] = useState(false);

  const [timeEndVisible, setTimeEndVisible] = useState(false);
  const [timeType, setTimeType] = useState();
  const [params, setParams] = useState({
    startTime: dayjs().subtract(151, 'day').format('YYYY-MM-DD'),
    endTime: dayjs().add(31, 'day').startOf('day').format('YYYY-MM-DD'),
    auditState: "",
    pageSize: 10,
    date: "",
    isShare: ""
  });
  const { listData, refreshing, empty, loadMore, onPull, onLoad } = usePage({
    request: pageHidden,
    params,
  });

  const [shenqStatus, setShenqStatus] = useState([
    {
      id: '',
      name: "全部",
      color: '#FF1616',
      bgColor: 'rgba(255, 148, 148, 0.5)'
    },
    {
      id: 2,
      name: "未分享",
      color: '#FF1616',
      bgColor: 'rgba(255, 148, 148, 0.3)'
    },
    {
      id: 1,
      name: "已分享",
      color: 'rgba(7, 193, 96, 1)',
      bgColor: 'rgba(176, 255, 214, 0.35)'
    },
  ]);

  useEffect(() => {
    Taro.eventCenter.on('reList', handleUpdate);

    return () => {
      Taro.eventCenter.off('reList', handleUpdate);
    }
  }, [])

  const handleUpdate = () => {
    setParams({
      ...params,
      date: new Date()
    })
  }

  const navigateToDetails = (item) => {
    navigateTo('/pages/danger-detail/index', item)
  };

  function selectTime(type) {
    setTimeType(type);
    if (type === "start") {
      setTimeStartVisible(true);
    } else {
      setTimeEndVisible(true);
    }
  }

  function confirmTime(values, options) {
    console.log(values, options);
    let data = ""
    if (values.join("-").includes("02-31") || values.join("-").includes("02-30")) {
      data = dayjs().year() + '-02-01'
    } else {
      data = values.join("-")
    }
    if (timeType === "start") {
      setParams({
        ...params,
        startTime: data
      })
    } else {
      setParams({
        ...params,
        endTime: data
      })
    }
  }

  const [visible, setVisible] = useState(false)
  const [baseDesc, setBaseDesc] = useState('')
  const listData1 = [
  [
      { value: "", text: '全部' },
      { value: 2, text: '未分享' },
      { value: 1, text: '已分享' },
    ],
  ]

  const changePicker = (list, option, columnIndex) => {
    console.log(columnIndex, option)
  }
  const confirmPicker = (
    options,
    values
  ) => {
    setParams({
      ...params,
      isShare: values[0] ? parseInt(values[0]) : ""
    })
  }

  function matchType(type) {
    for (let index = 0; index < shenqStatus.length; index++) {
      const element = shenqStatus[index];
      if (element.id == type) {
        return element
      }

    }
  }

  const showShareImageMenu = (path) => {
    if (Taro.showShareImageMenu) {
      Taro.showShareImageMenu({
        path: path,
        complete(){
          handleUpdate()
        },
      }).then().catch((err) => {
        console.log(err)
        const { errMsg } = err
        // 取消操作  errMsg === 'showShareImageMenu:fail cancel'
        // 拒绝授权  errMsg: "showShareImageMenu:fail auth deny"
        if (errMsg === 'showShareImageMenu:fail auth deny') {
          authorize({
            scope: 'writePhotosAlbum',
            showModal: true,
            authName: '保存图片到相册',
            success: () => {
              // this.downloadImg()
            },
          })
        }
      }).finally(() => {
        handleUpdate()
        // this.isDraw = false
      })
    } else {
      Taro.showToast({
        title: '小程序版本不支持该功能',
        icon: 'error',
      })
    }
  }

  const { statusBarHeight } = useNavInfo();
  // useEffect(()=>{
  //   Taro.getLocation({
  //     type: 'gcj02', //返回可以用于wx.openLocation的经纬度
  //     success (res) {
  //       const latitude = res.latitude
  //       const longitude = res.longitude
  //       Taro.openLocation({
  //         latitude,
  //         longitude,
  //         scale: 18
  //       })
  //     }
  //    })
  // })


  const jietu = async (e, item) => {
    e.stopPropagation()
    Taro.showLoading()
    const { success, data } = await shareWord({ id: item.id, urlPrefix: baseUrl })
    if (success) {
      Taro.downloadFile({
        // url:'https://yxxf.guojutech.net/api/image/show/videoDir/960805106398400512.jpg',
        url: data.shareQrUrl,
        success(res) {
          console.log(res);
          if (res.statusCode === 200) {
            const ctx = Taro.createCanvasContext('myCanvas')
            // 设置画布背景颜色为天蓝色
            ctx.fillStyle = "#87ceeb";
            // 填充整个画布
            ctx.fillRect(0, 0, 300, 400);

            ctx.fillStyle = "#ffffff";
            ctx.setFontSize(22)
            ctx.fillText('现场核查调派单', 70, 60)

            ctx.drawImage(res.tempFilePath, 66, 90, 170, 170)
            // ctx.drawImage(logo, 126, 150, 48, 48)
            ctx.fillStyle = "#ffffff";
            ctx.setFontSize(18)
            ctx.fillText('识别二维码下载', 84, 310)
            ctx.draw()
            Taro.hideLoading()
            Taro.canvasToTempFilePath({
              canvasId: 'myCanvas',
              success: (res) => {
                console.log(res);
                showShareImageMenu(res.tempFilePath)
              },
              
            })

          }

        }
      })

    }else{
      Taro.hideLoading()
    }




    // Taro.createSelectorQuery().select("#target").node().exec(res => {
    //   console.log(res);
    //   const node = res[0].node
    //   node.takeSnapshot({
    //     type: 'arraybuffer',
    //     format: 'png',
    //     success: (ress) => {
    //       console.log(ress);
    //       const f = `${Taro.env.USER_DATA_PATH}/hello.png`
    //       const fs = Taro.getFileSystemManager();
    //       fs.writeFileSync(f, ress.data, 'binary')
    //       Taro.showShareImageMenu({ path: f, })
    //     }
    //   })
    // })
  }


  const [shareImg, setShareImg] = useState('')

  const clearTimeout = () => {
    setParams({
      ...params,
      startTime: "",
      endTime: "",
    })
  }

  return (
    <View className={"reservation-record-page"}>

      <View>
        <Canvas className="myCanvas" canvasId="myCanvas" width={'300px'} height={'400px'}></Canvas>
      </View>
      <View className="topSelectWrap">
        <View className="timeWrap">
          <Image src={iconClockBlack} className="clockSty" />
          <Text className="timeText" onClick={() => selectTime("start")}>
            {params.startTime || '请选择'}
          </Text>
          <Text className="zhi">至</Text>
          <Text className="timeText" onClick={() => selectTime('end')}>{params.endTime  || '请选择'}</Text>
          <Image onClick={() => clearTimeout()} src={iconClear} className="iconClose" />
        </View>
        <View className="shai" onClick={() => {
          setVisible(true)
        }}>
          <Text>{matchType(params.isShare).name}</Text>
          <Image src={iconDownGray} className="downSty" />
        </View>
      </View>

      <View className={"list-wrapper"}>
        <InfiniteLoading
          empty={empty}
          onLoad={onLoad}
          onRefresh={onPull}
          refreshing={refreshing}
        >
          {listData?.map((item) => (
            <View
              className={"list-item"}
              onClick={() => navigateToDetails(item)}
            >
              <View className="tie">
                <View className="iteWrap" style={{ flex: 1 }}>
                  <Text className="tit"> 上报时间：</Text>
                  <Text className="ites">
                    {item.createdAt}
                  </Text>
                  <Text className="reTypeText" style={{ color: matchType(item.isShare).color, backgroundColor: matchType(item.isShare).bgColor }}>
                    {item.isShare === 1 ? '已分享' : '未分享'}
                  </Text>
                </View>
              </View>
              
              <View className="content">
                <Text className="companyName">{item.content}</Text>
              </View>
              <View className="xiaquWrap">
                <Image className="xiaqu" src={iconXiaqu}/>
                <Text className="jurisdiction">{item.jurisdiction}</Text>
              </View>
              <View className="btnWrap">
                {/* <Text>拒绝原因：{item.auditReason}</Text> */}
                <Text></Text>
                <Button onClick={(e) => jietu(e, item)} type="info" style={{}}>分享</Button>
              </View>


            </View>
          ))}
          {listData?.length > 0 && <InfiniteLoadingFoot state={loadMore} />}
        </InfiniteLoading>
      </View>

      {/* <Button className="AddBtn" block size="large" type="info" style={{}} onClick={() => {
        navigateTo("/pages/apply/index")
      }}>新增培训申请</Button> */}


      <DatePicker
        title="选择日期"
        visible={timeStartVisible}
        defaultValue={new Date(params.startTime)}
        showChinese
        onClose={() => {
          setTimeStartVisible(false);
        }}
        onConfirm={(options, values) => confirmTime(values, options)}
      />

      <DatePicker
        title="结束日期"
        visible={timeEndVisible}
        defaultValue={new Date(params.endTime)}
        showChinese
        onClose={() => { setTimeEndVisible(false) }}
        onConfirm={(options, values) => confirmTime(values, options)}
      />

      <Picker
        title="状态筛选"
        visible={visible}
        options={listData1}
        onConfirm={(list, values) => confirmPicker(list, values)}
        onClose={() => setVisible(false)}
        onChange={changePicker}
      />

      <ShareModal
        visible={shareVisible}
        close={() => {
          setShareVisible(false)
        }}
      />




    </View>
  );
}
